﻿using System.Threading.Tasks;
using MailService.Domain.Aggregate.Mail;
using MailService.Domain.Event;
using MailService.Domain.Repository;
using MailService.Domain.Shared.Enum;
using Microsoft.Extensions.Logging;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.Guids;

namespace MailService.Application.EventHandler
{
    /// <summary>
    /// 邮件发送事件处理
    /// </summary>
    public class RequireToTrustEmailEventHandler : IDistributedEventHandler<RequireToTrustEmailEvent>, ITransientDependency
    {
        private readonly ILogger<RequireToTrustEmailEventHandler> _logger;
        private readonly IMailRepository _mailRepository;
        private readonly IGuidGenerator _generator;
        
        public RequireToTrustEmailEventHandler(
            ILogger<RequireToTrustEmailEventHandler> logger,
            IMailRepository mailRepository,
            IGuidGenerator generator)
        {
            _logger = logger;
            _mailRepository = mailRepository;
            _generator = generator;
        }
        
        /// <summary>
        /// 处理事件
        /// </summary>
        public async Task HandleEventAsync(RequireToTrustEmailEvent eventData)
        {
            _logger.LogInformation($"用户：{eventData.UserId} 请求发送邮件，用户邮箱：{eventData.Email}");
            
            // 持久化邮件信息
            var mail = new Mail(_generator.Create(), 
                eventData.UserId, eventData.Email, MailSubject.MAIL_SUBJECT_VERIFY_YOU_EMAIL);
            // 暂存验证码
            mail.ExtraProperties.Add("verify", eventData.VerifyCode);
            mail.ExtraProperties.Add("user", eventData.UserName);

            // 持久化调用本地事件总线，转交MailPersistEventHandler进行处理
            await _mailRepository.InsertAsync(mail);
        }
    }
}